/**
   * ZUSTAND中文文档地址('https://awesomedevin.github.io/zustand-vue/docs/introduce/start/zustand')
   * ZUSTAND官网地址('https://docs.pmnd.rs/zustand/getting-started/introduction')
**/

import { create } from 'zustand';
import { loginApi, getUserApi } from '@/api/user/user';
import { message } from 'antd';
const copyData = (time: number) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(200)
    }, time)
  })
}

const useStore = create((set) => ({
  count: 0,
  userInfo: '',
  theme:localStorage.getItem('theme') ? JSON.parse(localStorage.getItem('theme') || '') : 'light',
  increment: () => set((state: any) => ({ count: state.count + 1 })),
  decrement: () => set((state: any) => ({ count: state.count - 1 })),
  asyncIncrement: async () => {
    let res = await copyData(300)
    if (res == 200) {
      set((state: any) => ({ count: state.count + 1 }))
    }
  },
  // 登录逻辑
  login: (params: LoginApiReq) => {
    return new Promise(async (resolve, reject) => {
      let loginApiRes = await loginApi(params)
      if (loginApiRes.code == 200) {
        message.open({
          type: 'success',
          content: '登录成功',
          duration: 2.5,
        });
        //   保存用户信息
        set(() => ({ userInfo: loginApiRes.userInfo[0] }))
        //   保存token
        localStorage.setItem('token', loginApiRes.token)
        // 删除captchaToken
        localStorage.removeItem('captchaToken')
        resolve(200)
        // 跳转页面
      } else {
        message.open({
          type: 'error',
          content: loginApiRes.msg,
          duration: 2.5,
        });
        reject(201)
      }

    })
  },
  // 获取用户信息验证token
  getUser: () => {
    return new Promise(async (resolve, reject) => {
      let getUserRes = await getUserApi()
      if (getUserRes.code == 200) {
        // token验证不过期
        set(() => ({ userInfo: getUserRes.userInfo}))
        resolve(200)
      } else {
        // token过期
        localStorage.removeItem('token')
        resolve('令牌过期,请重新弄登录')
      }
    })
  },
  ctheme:()=>{
    let theme = localStorage.getItem('theme') ? JSON.parse(localStorage.getItem('theme') || '') : 'light'
    if(theme == 'dark'){
      set(() => ({ theme: 'dark'}))
    }else{
      set(() => ({ theme: 'light'}))
    }
    
    // set((state: any) => {
    //   if(state.theme == 'light'){
    //     return state.theme == 'dark'
    //   }else{
    //     return state.theme == 'light'
    //   }
     
    // })
  }
})
)


export default useStore
